﻿using ProjectCommonLibs.consts;
using ProjectCommonLibs.models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ProjectCommonLibs.utils
{
    public class DataOptimizeUtils
    {
        public static List<RoofPhotovoltaicModel> optimizePhotoData(List<RoofPhotovoltaicModel> origin){
            var dic = new Dictionary<string, List<long>>();
            origin.ForEach(r => dic.Add(r.time, r.converterData));
            var optimizedData = optimizeDataDictionary(
                dic, //.Where(r => !DataCheckUtils.containsError(r.Value, DataCheckThreshoulds.photoThreshould))
                34);
            return (from 
                    item in optimizedData
                    select new RoofPhotovoltaicModel() {time = item.Key,converterData = item.Value })
                    .ToList();
        }
        public static List<RoofWeatherModel> optimizeWeatherData(List<RoofWeatherModel> origin)
        {
            var dic = new Dictionary<string, List<long>>();
            origin.ForEach(r => dic.Add(r.time, r.weatherData));
            var optimizedData = optimizeDataDictionary(
                dic,  //.Where(r => !DataCheckUtils.containsError(r.Value, DataCheckThreshoulds.weatherThreshould))
                6);
            return (from  
                    item in optimizedData
                    select new RoofWeatherModel() { time = item.Key, weatherData = item.Value })
                    .ToList();
        }

        private static Dictionary<string,List<long>> optimizeDataDictionary(IEnumerable<KeyValuePair<string,List<long>>> dataList,int length)
        {
            Dictionary<string, List<long>> resultDic = new Dictionary<string, List<long>>();
            List<long> optimizedData = new List<long>();
            if (dataList.Count() > 0)
            {
                var classifiedData = dataList.GroupBy(r => getCurrentMinute(r.Key));
                foreach (var item in classifiedData)
                {
                    optimizedData = new List<long>();
                    for (int i = 0; i < length; i++)
                    {
                        if (item.All(r => r.Value[i] == 0))
                        {
                            optimizedData.Add(0);
                        }
                        else
                        {
                            var noneZeroData = item.Where(r => !(r.Value[i] == 0));
                            optimizedData.Add((long)noneZeroData.Average(r => r.Value[i]));
                        }
                    }
                    resultDic.Add(item.Key,optimizedData);
                }
            }
            return resultDic;
        }

        private static string getCurrentMinute(string currentTime)
        {
            var times = currentTime.Split(':');
            return $"{times[0]}:{times[1]}";
        }
    }
}
